// 列表数据树形结构化
export function formatDataTree(data, topPid){
  let parents = data.filter(item => item.pid === topPid );
  let children = data.filter(item => item.pid !== topPid);
  dataToTree(parents,children);
  return parents;
}

// 树形结构化递归函数
function dataToTree(parents,children){
  parents.map(item => {
    children.map((inow,index) => {
      if(item.id === inow.pid){
        let _children = JSON.parse(JSON.stringify(children));
        _children.splice(index,1);
        if(item.children){
          item.children.push(inow);
        }else{
          item['children'] = [ inow ];
        }
        dataToTree([ inow ], _children);
      }
    });
  });
}

// 列表数据树形结构化 （非递归方案）
export function noRecurForTree(data, topPid){
  let _data = JSON.parse(JSON.stringify(data));
  let treeData = _data.filter(item => {
    let _arr = _data.filter(inow => item.id == inow.pid);
    _arr.length && (item.children = _arr);
    return item.pid === topPid;
  });
  return treeData;
}

// 列表数据数据扁平化
export function arrFlatData(arr){
  let newData = [];
  return treeToData(arr,newData);
}

// 数组扁平化递归逻辑
function treeToData(arr,newData){
  arr.map(item => {
    if(item.children){
      let _children = JSON.parse(JSON.stringify(item.children));
      delete item.children;
      newData.push(item);
      _children.map(inow => {
        treeToData([ inow ],newData);
      });
    }else{
      newData.push(item);
    }
  });
  return newData;
}

// 表单自动校验函数（内部引用$notify，必须注册到Vue全局）
export function formAutoVerify(formData,formKey){
  let varifyBool = true;
  // eslint-disable-next-line
  loop:for(let i=0; i< formData.length; i++){
    let item = formData[i];
    let picVerify = [ 'upload','custom-upload' ].includes(item.type) && formKey[item.id] && formKey[item.id].length<1;
    if(item.require && (!formKey[item.id] || picVerify)){
      this.$notify({ type: 'danger', message: (item.placeholder || `${ item.label }不能为空`) });
      varifyBool = false;
      break loop;
    }
    if(item.verify && item.verify.length){
      for(let j=0; j<item.verify.length; j++){
        let inow = item.verify[j];
        if(!inow.rule.test(formKey[item.id])){
          this.$notify({ type: 'danger', message: (inow.msg || `${ item.label }不符合规范`) });
          varifyBool = false;
          break loop;
        }
      }
    }
  }
  return varifyBool;
}
